<?php
/**
 * Created by PhpStorm.
 * User: 王峥宇
 * Date: 2019-04-24
 * Time: 13:34
 */

namespace app\admin\model;


use app\admin\controller\Base;
use think\Db;
use think\Model;
use think\Session;
use app\admin\model\User as UserModel;

class Indent extends BaseModel
{
    //protected $hidden = ['z_createtime'];
//    protected $autoWriteTimestamp = true;
    //支付方式
    public function zPayType(){
        return $this->belongsTo('Zpaytype','zid','zid');
    }
    //状态
    public function sType(){
        return $this->belongsTo('Stype','sid','sid');
    }
    //信誉
    public function score(){
        return $this->belongsTo('Score','tid','tid');
    }
    //会员
    public function iUser(){
        return $this->belongsTo('User','uid','uid');
    }
    //自动对账
    public static function xiugai()
    {
        $file = \request()->file('excel');
        $info = $file->move(ROOT_PATH . 'upload' . DS . 'exel');
        $filename = ROOT_PATH . 'upload' . DS . 'exel/' . $info->getSaveName();
        $handle = fopen($filename, 'r');
        $arr2= array(0=>'time',1=>'zhai',2=>'jiao',3=>'china',4=>'money',5=>'jsmoney',6=>'jzmoney',7=>'bizhong',8=>'jizhang'
        ,9=>'zhichu',10=>'jibi',11=>'yue',12=>'name',13=>' ');
        while ($data = fgetcsv($handle)) {
            $arr[] = $data;
        }dump($arr);die;
        $arr3 = array();
        foreach ($arr as $k => $val)
        {
            if ($k < 7) {
                continue;
            }
            //如果最后一位没有空 改成13
            if(count($val)<14){
                unset($val);
            }else{
                foreach($val as $kk=>$vv){
                    $id[$arr2[$kk]] = $vv;
                }
                $arr3[] = $id;
            }
        }
        foreach ($arr3 as $v)
        {
            if(trim($v['jizhang'])!='')
            {
                $arr6 = UserModel::where('u_nickname',trim($v['name']))->find();
                $as[] = $arr6['uid'];
                //为当前用户的保证金添加数值
                $umoney = UserModel::where('uid',$arr6['uid'])->setInc('u_money',str_replace(',','',trim($v['jizhang'])));
                //为用户改变订单状态
                $din[] =  self::where('uid',$arr6['uid'])->update(['sid'=>3]);
            }
        }
    }
    //发单
    public static function getIndentIndex()
    {
        if(input('sub')){
            $cateid = input('cateid');
            $zid = input('zid');
            $key = input('key');
            $datemin = input('datemin', '');//最小时间
            $datemax = input('datemax', '');//最大的吧
            $where['z_createtime']=['>=','1970-01-01 00:00:00'];
            if (isset($datemin) && $datemin != '') {
                $where['z_createtime']=['>=', $datemin . ' 00:00:00'];
            }
            if (isset($datemax) && $datemax != '') {
                $where['z_createtime']=['<=', $datemax . ' 23:59:59'];
            }
            if($zid != ''){
                $where['zid']=[
                    'like',
                    '%'.$zid.'%'
                ];
            }
            if($cateid=='t_number'){
                $where['t_number']=[
                    'like',
                    '%'.$key.'%'
                ];
            }else if($cateid=='z_name'){
                $where['z_name']=[
                    'like',
                    '%'.$key.'%'
                ];
            }
            $arr=self::with('zPaytype,sType')->where($where)->order('tid','desc')->paginate(12);
            return $arr;
        }
        $b=self::with('zPaytype,sType')->order('tid','desc')->paginate(12);
        return $b;
    }
    //搜索
    public static function search($where){

    }
    //添加订单
    public static function getInsert()
    {
        $data['zid'] = input('zid');
        $data['t_money'] = input('t_money');
        $data['t_number'] = getRandChar(32);
        $data['sid'] = config('stats.sid');
        $data['z_name'] = input('uname');
        $data['z_createtime'] = date('Y-m-d H:i:s');
        $inserts = self::insert($data);
        if ($inserts){
            return self::getLastInsID();
        }else{
            return 0;
        }
    }
    //修改订单
    public static function getUpdate(){
        $tid = input('tid');
        $b=self::with('zPaytype,sType')->where('tid',$tid)->find();
        if (request()->isAjax()) {
            $data['zid'] = input('zid');
            $data['t_money'] = input('t_money');
            $updateO = self::where('tid', $tid)->update($data);
            if ($updateO) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return $b;
        }
    }
    //匹配成功
    public static function getSuccIn(){
        $gid = Session::get('admin_uid');
        $user = new User();
        $gl = new Guanli();
        $gl=$gl->where('id',$gid)->find();
        $u = $user->where('uid',$gl['uid'])->find();
        $where=[];
        if($u['daili']==1) {
            if (input('sub')) {
                $cateid = input('cateid');
                $zid = input('zid');
                $key = input('key');
                $datemin = input('datemin', '');//最小时间
                $datemax = input('datemax', '');//最大的吧
                if (isset($datemin) && $datemin != '') {
                    $where['z_jietime'] = ['>=', $datemin . ' 00:00:00'];
                }
                if (isset($datemax) && $datemax != '') {
                    $where['z_jietime'] = ['<=', $datemax . ' 23:59:59'];
                }
                if ($zid != '') {
                    $where['zid'] = [
                        'like',
                        '%' . $zid . '%'
                    ];
                }
                if ($cateid == 't_number') {
                    $where['t_number'] = [
                        'like',
                        '%' . $key . '%'
                    ];
                }
                $arr = self::alias('a')
                    ->join('jc_user b', 'a.uid=b.uid', 'left')
                    ->where('b.u_path', 'like', '%,' . $u['uid'] . ',%')
                    ->where($where)
                    //->whereOr('b.uid', $u['uid'])
                    ->where('sid', config('stats.successyuyue'))
                    ->paginate(12);
                return $arr;
            }
            $re = self::alias('a')
                ->join('jc_user b', 'a.uid=b.uid', 'left')
                ->where('b.u_path', 'like', '%,' . $u['uid'] . ',%')
                //->whereOr('b.uid', $u['uid'])
                ->where('sid', config('stats.successyuyue'))
                ->paginate(12);
            return $re;
        }else {
            if (input('sub')) {
                $cateid = input('cateid');
                $zid = input('zid');
                $key = input('key');
                $datemin = input('datemin', '');//最小时间
                $datemax = input('datemax', '');//最大的吧
                if (isset($datemin) && $datemin != '') {
                    $where['z_jietime'] = ['>=', $datemin . ' 00:00:00'];
                }
                if (isset($datemax) && $datemax != '') {
                    $where['z_jietime'] = ['<=', $datemax . ' 23:59:59'];
                }
                if ($zid != '') {
                    $where['zid'] = [
                        'like',
                        '%' . $zid . '%'
                    ];
                }
                if ($cateid == 't_number') {
                    $where['t_number'] = [
                        'like',
                        '%' . $key . '%'
                    ];
                }
                $arr = self::with('zPaytype,sType,iUser')->where($where)->order('tid', 'desc')->paginate(12);
                return $arr;
            }
            $b = self::with('zPaytype,sType,iUser')->where('sid', config('stats.successyuyue'))->order('tid', 'desc')->paginate(12);
            return $b;
        }
    }
    //打款成功
    public static function getSuccInMake(){
        $gid = Session::get('admin_uid');
        $user = new User();
        $gl = new Guanli();
        $gl=$gl->where('id',$gid)->find();
        $u = $user->where('uid',$gl['uid'])->find();
        if($u['daili']==1) {
            $where = [];
            if (input('sub')) {
                $cateid = input('cateid');
                $zid = input('zid');
                $key = input('key');
                $datemin = input('datemin', '');//最小时间
                $datemax = input('datemax', '');//最大的吧
                if (isset($datemin) && $datemin != '') {
                    $where['z_jietime'] = ['>=', $datemin . ' 00:00:00'];
                }
                if (isset($datemax) && $datemax != '') {
                    $where['z_jietime'] = ['<=', $datemax . ' 23:59:59'];
                }
                if ($zid != '') {
                    $where['zid'] = [
                        'like',
                        '%' . $zid . '%'
                    ];
                }
                if ($cateid == 't_number') {
                    $where['t_number'] = [
                        'like',
                        '%' . $key . '%'
                    ];
                }
                $arr = self::alias('a')
                    ->join('jc_user b', 'a.uid=b.uid', 'left')
                    ->where('b.u_path', 'like', '%,' . $u['uid'] . ',%')
                    ->where($where)
                   // ->whereOr('b.uid', $u['uid'])
                    ->where('sid', config('stats.successdakuan'))
                    ->paginate(12);
                return $arr;

            }else {
                $re = self::alias('a')
                    ->join('jc_user b', 'a.uid=b.uid', 'left')
                    ->where('b.u_path', 'like', '%,' . $u['uid'] . ',%')
                    //->whereOr('b.uid', $u['uid'])
                    ->where('sid', config('stats.successdakuan'))
                    ->paginate(12);
                return $re;
            }
        }else {
            $where['sid'] = config('stats.successdakuan');
            if(input('sub')){
                $cateid = input('cateid');
                $zid = input('zid');
                $key = input('key');
                $datemin = input('datemin', '');//最小时间
                $datemax = input('datemax', '');//最大的吧
                if (isset($datemin) && $datemin != '') {
                    $where['z_jietime']=['>=', $datemin . ' 00:00:00'];
                }
                if (isset($datemax) && $datemax != '') {
                    $where['z_jietime']=['<=', $datemax . ' 23:59:59'];
                }
                if($zid != ''){
                    $where['zid']=[
                        'like',
                        '%'.$zid.'%'
                    ];
                }
                if($cateid=='t_number'){
                    $where['t_number']=[
                        'like',
                        '%'.$key.'%'
                    ];
                }
                $arr=self::with('zPaytype,sType,iUser')->where($where)->order('tid','desc')->paginate(12);
                return $arr;
            }
            $b = self::with('zPaytype,sType,iUser')->where($where)->order('tid', 'desc')->paginate(12);
            return $b;
        }
    }
    //交易成功
    public static function getSuccPay(){
        $gid = Session::get('admin_uid');
        $user = new User();
        $gl = new Guanli();
        $gl=$gl->where('id',$gid)->find();
        $u = $user->where('uid',$gl['uid'])->find();
        $where=[];
        if($u['daili']==1) {
            if (input('sub')) {
                $cateid = input('cateid');
                $zid = input('zid');
                $key = input('key');
                $datemin = input('datemin', '');//最小时间
                $datemax = input('datemax', '');//最大的吧
                if (isset($datemin) && $datemin != '') {
                    $where['z_jietime'] = ['>=', $datemin . ' 00:00:00'];
                }
                if (isset($datemax) && $datemax != '') {
                    $where['z_jietime'] = ['<=', $datemax . ' 23:59:59'];
                }
                if ($zid != '') {
                    $where['zid'] = [
                        'like',
                        '%' . $zid . '%'
                    ];
                }
                if ($cateid == 't_number') {
                    $where['t_number'] = [
                        'like',
                        '%' . $key . '%'
                    ];
                }
                $arr = self::alias('a')
                    ->join('jc_user b', 'a.uid=b.uid', 'left')
                    ->where('b.u_path', 'like', '%,' . $u['uid'] . ',%')
                    ->where($where)
                    // ->whereOr('b.uid', $u['uid'])
                    ->where('sid', config('stats.successpay'))
                    ->paginate(12);
                return $arr;
            }
            $re = self::alias('a')
                ->join('jc_user b', 'a.uid=b.uid', 'left')
                ->where('b.u_path', 'like', '%,' . $u['uid'] . ',%')
                //->whereOr('b.uid', $u['uid'])
                ->where('sid', config('stats.successpay'))
                ->paginate(12);
            return $re;
        }else {
            $where['sid']=config('stats.successpay');
            if (input('sub')) {
                $cateid = input('cateid');
                $zid = input('zid');
                $key = input('key');
                $datemin = input('datemin', '');//最小时间
                $datemax = input('datemax', '');//最大的吧
                if (isset($datemin) && $datemin != '') {
                    $where['z_jietime'] = ['>=', $datemin . ' 00:00:00'];
                }
                if (isset($datemax) && $datemax != '') {
                    $where['z_jietime'] = ['<=', $datemax . ' 23:59:59'];
                }
                if ($zid != '') {
                    $where['zid'] = [
                        'like',
                        '%' . $zid . '%'
                    ];
                }
                if ($cateid == 't_number') {
                    $where['t_number'] = [
                        'like',
                        '%' . $key . '%'
                    ];
                }
                $arr = self::with('zPaytype,sType,iUser')->where($where)->order('tid', 'desc')->paginate(12);
                return $arr;
            }
            $b = self::with('zPaytype,sType,iUser')->where($where)->order('tid', 'desc')->paginate(12);
            return $b;
        }
    }

    //匹配成功->打款成功
    public static function getSuccIndk(){
        $tid = input('tid');
        $data['sid'] = config('stats.successdakuan');
        $data['z_datime'] = date('Y-m-d H:i:s');
        $indent = self::where('tid',$tid)->update($data);
        if ($indent){
            return 1;
        }else{
            return 2;
        }
    }

    /*
      * 匹配成功->打款成功 :改变匹配成功时间，变为打款时间，改为打款状态
      * 打款成功->收款成功：收款生成收款时间，与打款时间比较大于5分钟得-1分
      * 小于5分钟得1分，基础分值为0分，负分记为0f分，改为收款状态
      * 打款成功->交易成功
      * 交易成功：需要改变会员的信誉额度，增加交易结束时间，改变交易状态
      */
    public static function getSuccInpay(){
        Db::startTrans();//事务开始
        $uid = input('uid');
        $tid = input('tid');
        $yid = input('yid');
        $sid = config('stats.successpay');
        $balancelog = new Balancelog();
        $balance=[];
        $succtime = date('Y-m-d H:i:s');
        $user = new User();
        $user = $user->where('uid',$uid)->find();
        $indent = self::where('tid',$tid)->find();
        $log = new Log();
        $mlog=[];
        $smailmoney = $user['lilv']*$indent['t_money'];//佣金
        $umoney=array_sum([$user['u_money'],$indent['t_money']]);
        $update = self::where('tid',$tid)
            ->update([
                'z_successtime' => $succtime,
                'sid' => $sid,
                't_usermoney' => $smailmoney
            ]);
        if(strtotime($indent['z_shoutime']) - strtotime($indent['z_datime'])>300){
            $scores = '-1';
            $type = 4;
        }else{
            $scores = '1';
            $type = 2;
        }
        $moneysome = $smailmoney;//刷单人所得佣金
        $balance[]=['uid'=>$uid,'type'=>1,'num'=>$indent['t_money'],'from_type'=>$type,'before_num'=>$user['u_money'],'after_num'=>$umoney,'memo'=>'','createtime'=>$succtime];//信用额度
        $balance[]=['uid'=>$uid,'type'=>2,'num'=>$moneysome,'from_type'=>$type,'before_num'=>$user['y_money'],'after_num'=>array_sum([$user['y_money'],$moneysome]),'memo'=>'','createtime'=>$succtime];//佣金
        $balance[]=['uid'=>$uid,'type'=>3,'num'=>$scores,'from_type'=>$type,'before_num'=>$user['score'],'after_num'=>array_sum([$user['score'],$scores]),'memo'=>'','createtime'=>$succtime];//信用分
        $mlog[]=['l_number'=>$indent['t_number'],'uid'=>$uid,'zid'=>$indent['zid'],'l_yongjin'=>$moneysome,'w_createtime'=>$succtime];
        if($user['daili']==1){
            $moneysome = $smailmoney;
            $user->where('uid',$uid)->update(['y_money'=>array_sum([$user['y_money'],$moneysome])]);
            $log->insert($mlog);
            $balancelog->insertAll($balance);
        }else{
            $path = array_filter(explode(',',$user['u_path']));
            foreach ($path as  $v){
                $dai = $user->where('uid',$v)->find();
                if($dai['did'] == 1){
                    $li = $dai['uid'];
                    $lv = $dai['lilv'];
                }
            }
            if($li!=''){
                $moneysomeD = $lv*$indent['t_money']-$smailmoney;//代理所得佣金
                $user->where('uid',$li)->update(['y_money'=>array_sum([$user['y_money'],$moneysomeD])]);
                $user->where('uid',$uid)->update(['y_money'=>array_sum([$user['y_money'],$moneysome])]);
                $mlog[]=['l_number'=>$indent['t_number'],'uid'=>$li,'zid'=>$indent['zid'],'l_yongjin'=>$moneysomeD,'w_createtime'=>$succtime];
                $balance[]=['uid'=>$li,'type'=>2,'num'=>$moneysomeD,'from_type'=>$type,'before_num'=>$user['y_money'],'after_num'=>array_sum([$user['y_money'],$moneysomeD]),'memo'=>'','createtime'=>$succtime];
                $log->insertAll($mlog);
                $balancelog->insertAll($balance);
            }else{
                $moneysome = $smailmoney;
                $user->where('uid',$uid)->update(['y_money'=>array_sum([$user['y_money'],$moneysome])]);
                $log->insert($mlog);
                $balancelog->insertAll($balance);
            }
        }
        if($update){
            $u=$user->where('uid',$uid)->update(['u_money'=>$umoney,'score'=>array_sum([$user['score'],$scores])]);
            $sor = [];
            $sor[]= ['e_score' => $scores,
                'uid' => $uid,
                'tid' => $tid,
                'e_createtime' => $succtime
            ];
            $score = new Score();
            $score = $score->insertAll($sor);
            $yuyue = new Yue();
            $yuuu=$yuyue->where('yid',$yid)->update(['y_state'=>1]);
            if($score && $u &&$yuuu){
                Db::commit();
                return 1;
            }else{
                Db::rollback();
                return 2;
            }
        }else{
            return 2;
        }

    }

}